package com.caiyi.financial.nirvana.sms.gateway.sgip.handler;

import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.gateway.sgip.SGIPClient;
import com.caiyi.financial.nirvana.sms.gateway.sgip.message.SGIPMessage;
import com.caiyi.financial.nirvana.sms.gateway.sgip.message.body.SGIPBindResp;
import com.caiyi.financial.nirvana.sms.gateway.sgip.message.body.SGIPSubmitResp;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SGIPReceiverHandler extends SimpleChannelInboundHandler<SGIPMessage> {

    private static final Logger logger = LoggerFactory.getLogger(SGIPReceiverHandler.class);

    private SGIPClient client;

    public SGIPReceiverHandler(SGIPClient client) {
        this.client = client;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SGIPMessage msg) throws Exception {
        int commandId = msg.getCommandID();
        switch (commandId) {
            //连接回应
            case SGIPMessage.SGIP_BIND_RESP:
                handleSGIPConnected((SGIPBindResp) msg.getBody());
                break;
            //获得消息发送返回值
            case SGIPMessage.SGIP_SUBMIT_RESP:
                int seqId = msg.getSequenceId();
                String remoteMsgId = Long.toHexString(msg.getMessageId());
                SGIPSubmitResp resp = (SGIPSubmitResp) msg.getBody();
                handleSubmitResponse(resp.getResult(), seqId, remoteMsgId);
                break;
            default:
                break;
        }
    }

    //处理连接响应
    private void handleSGIPConnected(SGIPBindResp response) {
        int status = response.getStatus();
        if (status == 0) {
            client.loginSuccess();
            return;
        }
        logger.info("网关【{}】登录失败，回复状态：{}", client.info.getName(), status);
        if (status > 5) {
            status = 5;
        }
        client.loginFail(response.getStatus(), SGIPBindResp.STATUS.get(status));
    }

    private void handleSubmitResponse(int result, int seqId, String remoteMsgId) {
        String messageId = client.S2M.remove(String.valueOf(seqId));
        int status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
        if (result != 0) {
            status = SmsMsgStatusEnum.REQUEST_FAIL.index;
            logger.info("handleSummitResponse result : {}, seqId : {}, remoteMsgId : {}", result, seqId, remoteMsgId);
            this.client.onSubmitResponse(status, messageId, String.valueOf(result));
            return;
        }
        JedisService.hset(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, remoteMsgId, messageId);
        this.client.onSubmitResponse(status, messageId, remoteMsgId);
    }
}
